<?php


namespace api\web\middleware;


use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class CheckToken
{
    public function handle($request,\Closure $next){
        //验证token是否正确
        $header = request()->header();
    if(!isset($header['token'])||empty($header['token'])){
        return json(['code'=>0,'msg'=>'缺少token!']);
    }
        $key = new Key(config('app.jwt_key'),'HS256');
        try {
            $res = JWT::decode($header['token'],$key);
        }catch (\Exception $exception) {
            return json(['code' => 0,'msg' => $exception->getMessage()]);
        }
        $request->userId=$res->data->user_id;
        return $next($request);
    }
}